<template>
	<div class="page bg-white">
        <el-select v-model="checkOptionsList" multiple placeholder="请选择" size="small">
            <el-option v-for="item in departmentList" :key="item.id"  :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-button size="small" type="primary" @click="moreDepartment">确 定</el-button>
        <el-button size="small" @click="resetList">清空</el-button>
        <div style="width:100%;text-align:center;font-weight:600;font-size:20px;margin-bottom:10px"><p>{{currentYears}}年{{fatherMeanName}}费用报表</p></div>
        <el-tabs type="border-card" @tab-click="handleClick" v-model="handleClickNum" style="height:100%">
            <el-tab-pane :key="index" v-for="(item, index) in optionsList" :label="item.name" :name="item.id">
                <div class="top">
                    <el-table el-table :data="alldata" :span-method="arraySpanMethod" :cell-style="cellStyle"
                            style="border: 1px solid #d6cfe2;" v-loading="ListLoading"
                            :header-cell-class-name="cellHeadStyle" :summary-method="getSummaries" show-summary
                            size="small" border>
                        <el-table-column prop label="费用明细" width="180" fixed="left">
                            <el-table-column prop="name" label="大类" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <el-link :underline="false"  @click="getClassa(scope.row)">{{scope.row.name}}</el-link>
                                </template>
                            </el-table-column>
                            <el-table-column prop="name1" label="小类" show-overflow-tooltip></el-table-column>
                        </el-table-column>
                        <el-table-column prop="January" label="1月" align="center" @click="amountDetails" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'01')">{{scope.row.January}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="February" label="2月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'02')">{{scope.row.February}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="March" label="3月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'03')">{{scope.row.March}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="April" label="4月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'04')">{{scope.row.April}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="May" label="5月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'05')">{{scope.row.May}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="June" label="6月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'06')">{{scope.row.June}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="July" label="7月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'07')">{{scope.row.July}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="August" label="8月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'08')">{{scope.row.August}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="September" label="9月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'09')">{{scope.row.September}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="October" label="10月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'10')">{{scope.row.October}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="November" label="11月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'11')">{{scope.row.November}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="December" label="12月" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false"   @click="amountDetails(scope.row ,'12')">{{scope.row.December}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="total" label="合计" align="center" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="remarka" label="备注" width="250" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <div style="display:flex">
                                    <div style="flex:1">{{scope.row.remarka}}</div>
                                    <el-button v-if="RemarksPermissions==='0'" type="text" size="mini" @click="updateRemarksOld(scope.row)">修改</el-button>
                                </div>
							</template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-tab-pane>
        </el-tabs>
        <el-dialog width="50%" :visible.sync="costDetailDialog" v-dialogDrag :title="costTitle+'费用明细'">
            <el-table :data="costDetailList" :cell-style="cellStyle"
                    style="border: 1px solid #d6cfe2;"
                    :header-cell-class-name="cellHeadStyle"
                    :row-class-name="tableRowClassName"  :summary-method="getSummaries" show-summary
                     size="small"
                    class="table">
                        <!-- <el-table-column prop="threeHeader" label="费用明细" align="center"/> -->
                        <el-table-column prop="strdate" label="时间" align="center" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="department.name" label="部门" align="center" show-overflow-tooltip></el-table-column>
                        <!-- <el-table-column prop="userName" label="人员" align="center"/> -->
                        <el-table-column prop="money" label="金额" align="center" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-link :underline="false" @click="threeAmountDetails(scope.row)">{{scope.row.money}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="remarks" label="备注" show-overflow-tooltip></el-table-column>
                    </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="costDetailDialog=false">关闭</el-button>
                <el-button size="small" type="primary" @click="costDetailDialog=false">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog width="50%" :visible.sync="threeCostDetailDialog"  v-dialogDrag :title="costTitle+'费用明细'">
            <el-table :data="threeCostDetailList" :cell-style="cellStyle" 
                    style="border: 1px solid #d6cfe2;"
                    :header-cell-class-name="cellHeadStyle"
                    :row-class-name="tableRowClassName"  :summary-method="getSummaries" show-summary
                     size="small"
                    class="table">
                        <el-table-column prop="classc.name" label="费用明细" align="center" show-overflow-tooltip/>
                        <el-table-column prop="strdate" label="时间" align="center" show-overflow-tooltip/>
                        <!-- <el-table-column prop="department" label="部门" align="center"/> -->
                        <el-table-column prop="user.name" label="人员" align="center" show-overflow-tooltip/>
                        <el-table-column prop="money" label="金额" align="center" show-overflow-tooltip/>
                        <el-table-column prop="remarks" label="备注" show-overflow-tooltip/>
                    </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="threeCostDetailDialog=false">关闭</el-button>
                <el-button size="small" type="primary" @click="threeCostDetailDialog=false">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog width="30%" :visible.sync="updateRemarkslDialog" v-dialogDrag title="备注" >
            <el-form ref="editRemarks">
                <el-form-item  size="small" label="备注" label-width="80px" prop="remarks">
                    <el-input v-model="editRemarks.remarks" type="textarea" ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="updateRemarkslDialog=false">关闭</el-button>
                <el-button size="small" type="primary" @click="updateRemarks">确 定</el-button>
            </div>
        </el-dialog>
	</div>
</template>
<script>
	import tableStyles from "../../../../utils/mixins.js";
	export default {
		mixins: [tableStyles],
		data() {
			return {
                costTitle:"",//明细弹框标题（动态）
                department:"",//部门id
                ListLoading:false,
                currentYears:"",//当前年
                currentMonths:"",//当前月
                amountDetailsId:"",
                handleClickNum:"0",
                checkOptionsList:"",
                departmentList:[],
                optionsList:[//选项卡（总表、部门、项目..）
                    {
                        id:"0",
                        name: '费用总表',
                    }
                ],
                alldata:[],//费用列表
                list:[],//费用列表数据解析前列表
                costDetailDialog:false,//费用明细（费用汇总）
                costDetailList:[],
                //三级科目（部门/项目）
                threeCostDetailDialog:false,//费用明细（部门）
                threeCostDetailList:[],
                updateRemarkslDialog:false,//根据权限修改备注
                RemarksPermissions:"",
                editRemarks:{
                    id:"",
                    remarks:"",
                }

            }
		},
		// // 1. 获取后台数据
        created() {
        // 二次处理数据
            // this.alldata = this.handleTableArr(this.list);
        },
        computed:{
            fatherMeanName: {
                get () {
                    return this.$store.state.common.fatherMeanName
                }
            },
        },
        mounted(){
            this.getCurrentTime();
            this.getCompanyByOffice();
            this.getRemarksPermissions();
            this.getList().then(()=>{
                this.alldata = this.handleTableArr(this.list);
            })
            
        },
		methods: {
            moreDepartment(){
                console.log("搜索",this.checkOptionsList);
                this.department=this.checkOptionsList.join(',');
                this.getList().then(()=>{
                    this.alldata = this.handleTableArr(this.list);
                })
            },
            resetList(){
                this.checkOptionsList=[];
                this.department="";
                this.getList().then(()=>{
                    this.alldata = this.handleTableArr(this.list);
                })
            },
            //选项卡点击
            handleClick() {
                console.log(this.handleClickNum);
                this.classa="";
                if(this.handleClickNum!=0){
                    this.department=this.handleClickNum;
                    this.getList().then(()=>{
                    this.alldata = this.handleTableArr(this.list);
                    })
                }
                else{
                    this.department="";
                    this.getList().then(()=>{
                        this.alldata = this.handleTableArr(this.list);
                    })
                }
            },
            // 获取当前时间（年份）
            getCurrentTime() {
            　　this.currentYears = new Date().getFullYear(); 
            },
            //金额明细
            amountDetails(row,month){
                console.log(row,month);
                this.costTitle=row.name1
                this.currentMonths=month;
                this.amountDetailsId=row.id;
                this.costDetailDialog=true;
                this.$http({
                    url: "/rf/expensedetails/getList",
                    method: "get",
                    params: {
                        company: this.$store.state.user.companyId,
                        reportcost:this.amountDetailsId,    
                        department:this.department,
                        strdate:this.currentYears+"-"+this.currentMonths
                    },
                }).then(({ data }) => {
                    if (data && data.success) {
                        console.log("费用明细1",data.list)
                        this.costDetailList=data.list;
                    }
                });
            },
            threeAmountDetails(row, month){
                console.log(row);
                this.threeCostDetailDialog=true;
                this.$http({
                    url: "/rf/departmentdetails/getList",
                    method: "get",
                    params: {
                        company: this.$store.state.user.companyId,
                        department:row.department.id,
                        reportcost:this.amountDetailsId,
                        strdate:this.currentYears+"-"+this.currentMonths
                    },
                }).then(({ data }) => {
                    if (data && data.success) {
                        console.log("费用明细2",data.list)
                        this.threeCostDetailList=data.list;
                    }
                });
            },
            //查询部门（选项卡）
            getCompanyByOffice(){
                this.$http({
                    url: "/sys/office/getCompanyByOffice",
                    method: "get",
                    params: {
                        company: this.$store.state.user.companyId
                    },
                }).then(({ data }) => {
                    if (data && data.success) {
                        this.departmentList=data.List;
                        data.List.forEach(item =>{
                            console.log("便利数组",item)
                            this.optionsList.push(item);
                        })
                        
                        console.log("部门（选项卡）",data)
                    } else {
                    }
                });
            },
            getClassa(row){
                this.classa=row.classa;
                this.getList().then(()=>{
                    this.alldata = this.handleTableArr(this.list);
                }) 
            },
            //费用总表查询
            getList(){
                return new Promise((resolve, reject) => {
                    this.$http({
                        url: "/rf/report/getList",
                        method: "get",
                        params: {
                            company: this.$store.state.user.companyId,
                            department:this.department,
                            classa:this.classa
                        },
                    }).then(({ data }) => {
                        if (data && data.success) {
                            this.list=data.list;
                            console.log("费用总表1",this.list)
                            this.ListLoading = false;
                            
                        } else {
                            this.ListLoading = false;
                        }
                        resolve();
                    });
                })
                
            },
            //修改备注
            getRemarksPermissions(){
                this.$http({
                    url: "/rf/userjurisdiction/get",
                    method: "get",
                    params: {
                        id: this.$store.state.user.companyId
                    },
                }).then(({ data }) => {
                    if (data && data.success) {
                        console.log("查询权限",data)
                        this.RemarksPermissions=data.j;
                    }
                });
            },
            updateRemarksOld(row){
                console.log(row);
                this.updateRemarkslDialog=true;
                this.editRemarks.id=row.id;
                this.editRemarks.remarks=row.remarka;
            },
            updateRemarks(){
                this.$http({
                    url: "/rf/report/updateRemarks",
                    method: "post",
                    params: {
                        id: this.editRemarks.id,
                        remarks:this.editRemarks.remarks,
                        type:"0"
                    },
                }).then(({ data }) => {
                    if (data && data.success) {
                        console.log(data);
                        this.getList().then(()=>{
                            this.alldata = this.handleTableArr(this.list);
                        })
                        this.updateRemarkslDialog=false;
                    }
                });
            },
			// 解析数据
            handleTableArr(data) {
                let arr = [];
                for (let i = 0; i < data.length; i++) {
                let category_info = data[i];
                let children = category_info["children"];
                let count = 0;
                for (let j = 0; j < children.length; j++){
                    let children1 = children[j];
                    let children2=[];
                    children2.push(children[j]["children"]);
                    console.log("children2",children2)
                    for (let k = 0; k < children2.length; k++){
                    count ++;
                        let info = {
                            // 确定每天数据的 合并行的数量
                            span_num: k === 0 ? children2.length : 0,
                            January:children2[k]["january"],
                            February:children2[k]["february"],
                            March:children2[k]["march"],
                            April:children2[k]["april"],
                            May:children2[k]["may"],
                            June:children2[k]["june"],
                            July:children2[k]["july"],
                            August:children2[k]["august"],
                            September:children2[k]["september"],
                            October:children2[k]["october"],
                            November:children2[k]["november"],
                            December:children2[k]["december"],
                            total:children2[k]["total"],
                            id:children2[k]["id"],
                            remarka:children2[k]["remarks"],
                            name1:children1["name"],
                            classa:category_info['id'],
                            name: category_info["name"],
                        };
                        arr.push(info);
                    }
                }
        // 第一列的合并数量, 赋值给每个大项的第一个单元格. 比如合格积分要合并 8 行.
                arr[arr.length - count]["count"] = count;
                }
                return arr;
            },
            // 表格合并的方法
            arraySpanMethod({row, column, rowIndex, columnIndex}) {
                // 第一列
                if (columnIndex === 0){
                if (row.count){
                    return [row.count, 1]
                }else{
                    return [0, 0]
                }
                }
            // 第二列
                if (columnIndex === 1){
                    if (row.span_num > 0 ){
                    return [row.span_num, 1]
                    }else{
                    return [0, 0]
                    }
                }
            },
            //总表合计
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '总计 (元)';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                    }, 0);
                    sums[index] += ' ';
                } else {
                    sums[index] = '';
                }
                });

                return sums;
            }
            
		}
	}
</script>
<style scoped>

</style>
